package com.szqhyxj.youxiangju.biz.realNameAuth;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;

import com.szqhyxj.youxiangju.biz.core.TokenManager;
import com.szqhyxj.youxiangju.biz.realNameAuth.bankcard.BankCardEntity;
import com.szqhyxj.youxiangju.biz.realNameAuth.bankcard.BankCardPresenter;
import com.szqhyxj.youxiangju.biz.realNameAuth.bankcard.BankList;
import com.szqhyxj.youxiangju.biz.realNameAuth.bankcard.CardInfo;
import com.szqhyxj.youxiangju.biz.realNameAuth.bankcard.RealNameMsmEntity;
import com.szqhyxj.youxiangju.biz.realNameAuth.idcard.IDCardBackInfo;
import com.szqhyxj.youxiangju.biz.realNameAuth.idcard.IDCardEntity;
import com.szqhyxj.youxiangju.biz.realNameAuth.idcard.IDCardFaceInfo;
import com.szqhyxj.youxiangju.sys.BaseResult;
import com.szqhyxj.youxiangju.sys.RetrofitFacade;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

public class RealNameModel {

    public interface RealNameService {

        @Multipart
        @POST("ocr/bankCard")
        Observable<BaseResult<CardInfo>> ocrBankCard(
                @Part MultipartBody.Part file,
                @Part("token") RequestBody token
        );

        @Multipart
        @POST("ocr/idCardFace")
        Observable<BaseResult<IDCardFaceInfo>> ocrIDCardFace(
                @Part MultipartBody.Part file,
                @Part("token") RequestBody token
        );

        @Multipart
        @POST("ocr/idCardBack")
        Observable<BaseResult<IDCardBackInfo>> orcIDCardBack(
                @Part MultipartBody.Part file,
                @Part("token") RequestBody token
        );

        @POST("bank/trunk/cardapplication")
        Observable<BaseResult<List<BankList>>> bankList();

        @FormUrlEncoded
        @POST("msg/sms/vercodesend")
        Observable<BaseResult> realNameSms(@Field("phone") String phone);

        @FormUrlEncoded
        @POST("user/certification/certidcard")
        Observable<BaseResult> IdCardcommit(
                @Field("username") String username,
                @Field("idCard") String idCard,
                @Field("certStateDate") String certStateDate,
                @Field("certExpireDate") String certExpireDate,
                @Field("faceUrl") String faceUrl,
                @Field("backUrl") String backUrl
        );

        @FormUrlEncoded
        @POST("user/certification/certuserbankcard")
        Observable<BaseResult> Cardcommit(
                @Field("username") String userName,
                @Field("bankCardNo") String bankCardNo,
                @Field("btCode") String btCode,
                @Field("btName") String btName,
                @Field("cardPhone") String cardPhone,
                @Field("bankCardPic") String bankCardPic,
                @Field("verCode") String verCode
        );


        @POST("user/certification/queryIdCard")
        Observable<BaseResult<IDCardEntity>> queryIdCard ();

    }

    public static Observable<BaseResult<IDCardEntity>> queryIdCard(){
        return RetrofitFacade.Companion.getRetrofit()
                .create(RealNameService.class)
                .queryIdCard();
    }
    public static Observable<BaseResult> ICcardcommit(IDCardEntity idCardEntity){
        return RetrofitFacade.Companion.getRetrofit()
                .create(RealNameService.class)
                .IdCardcommit(
                        idCardEntity.getUsername(),
                        idCardEntity.getIdCard(),
                        idCardEntity.getCertStateDate(),
                        idCardEntity.getCertExpireDate(),
                        idCardEntity.getFaceUrl(),
                        idCardEntity.getBackUrl()
                );
    }
    public static Observable<BaseResult> Cardcommit(BankCardEntity bankCardEntity){
        return RetrofitFacade.Companion.getRetrofit()
                .create(RealNameService.class)
                .Cardcommit(
                        bankCardEntity.getUsername(),
                        bankCardEntity.getBankCardNo(),
                        bankCardEntity.getBtCode(),
                        bankCardEntity.getBtName(),
                        bankCardEntity.getCardPhone(),
                        bankCardEntity.getBankCardPic(),
                        bankCardEntity.getVerCode()
                );
    }
    public static Observable<BaseResult<CardInfo>> ocrBankCard(File file) {
        MultipartBody.Part filePart = MultipartBody.Part.createFormData(
                "card",
                file.getName(),
                RequestBody.create(MediaType.parse("image/*"), file)
        );
        return RetrofitFacade.Companion.getUploadRetrofit().create(RealNameService.class)
                .ocrBankCard(filePart, getToken());
    }

    public static Observable<BaseResult<IDCardFaceInfo>> ocrIDCardFace(File file) {
        MultipartBody.Part filePart = MultipartBody.Part.createFormData(
                "face",
                file.getName(),
                RequestBody.create(MediaType.parse("image/*"), file)
        );
        return RetrofitFacade.Companion.getUploadRetrofit().create(RealNameService.class)
                .ocrIDCardFace(filePart, getToken());
    }

    public static Observable<BaseResult<IDCardBackInfo>> ocrIDCardBack(File file) {
        MultipartBody.Part filePart = MultipartBody.Part.createFormData(
                "back",
                file.getName(),
                RequestBody.create(MediaType.parse("image/*"), file)
        );
        return RetrofitFacade.Companion.getUploadRetrofit().create(RealNameService.class)
                .orcIDCardBack(filePart, getToken());
    }

    public static Observable<BaseResult<List<BankList>>> getBankList(){
        return RetrofitFacade.Companion.getRetrofit().create(RealNameService.class).bankList();
    }

    public static Observable<BaseResult> realNameSms(RealNameMsmEntity realNameMsmEntity){
        return RetrofitFacade.Companion.getRetrofit()
                .create(RealNameService.class)
                .realNameSms(
                      realNameMsmEntity.getPhone()
                );
    }

    /**
     * 新建一个图片（用来存储拍照的结果）
     * @param context
     * @return
     * @throws IOException
     */
    public static File createImageFile(Context context) throws IOException {
        @SuppressLint("SimpleDateFormat")
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
    }

    /**
     * 从文件获取 bitmap
     * @param context
     * @param file
     * @return
     * @throws IOException
     */
    public static Bitmap getBitmap(Context context, File file) throws IOException {
        Uri uri = Uri.fromFile(file);
        return MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
    }

    /**
     * 从 uri 获取 uri 对应的 bitmap 和文件路径
     * @param context
     * @param uri
     * @return
     */
    public static FileInfo getFileInfoFromUri(Context context, Uri uri) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        assert uri != null;
        Cursor cursor = context.getContentResolver().query(
                uri, filePathColumn, null, null, null
        );
        assert cursor != null;
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
        return new FileInfo(picturePath, bitmap);
    }

    public static class FileInfo {
        String path;

        Bitmap bitmap;

        FileInfo(String path, Bitmap bitmap) {
            this.path = path;
            this.bitmap = bitmap;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public Bitmap getBitmap() {
            return bitmap;
        }

        public void setBitmap(Bitmap bitmap) {
            this.bitmap = bitmap;
        }
    }


    @NonNull
    private static RequestBody getToken() {
        return RequestBody.create(MediaType.parse("text/plain"), TokenManager.INSTANCE.getMToken());
    }

}